package com.remotephone.myapplication

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.remotephone.myapplication.ui.theme.MyApplicationTheme
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class ScreenshotViewActivity : ComponentActivity() {
    
    companion object {
        const val EXTRA_SCREENSHOT_PATH = "screenshot_path"
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        val screenshotPath = intent.getStringExtra(EXTRA_SCREENSHOT_PATH)
        if (screenshotPath == null) {
            Toast.makeText(this, "截图路径不存在", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        
        setContent {
            MyApplicationTheme {
                ScreenshotViewScreen(
                    screenshotPath = screenshotPath,
                    onBack = { finish() },
                    onSave = { saveScreenshot(screenshotPath) }
                )
            }
        }
    }
    
    private fun saveScreenshot(screenshotPath: String) {
        try {
            val sourceFile = File(screenshotPath)
            if (!sourceFile.exists()) {
                Toast.makeText(this, "截图文件不存在", Toast.LENGTH_SHORT).show()
                return
            }
            
            // 保存到Pictures目录
            val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
            val fileName = "screenshot_$timestamp.png"
            val picturesDir = getExternalFilesDir("Pictures")
            val savedFile = File(picturesDir, fileName)
            
            sourceFile.copyTo(savedFile, overwrite = true)
            Toast.makeText(this, "截图已保存: ${savedFile.absolutePath}", Toast.LENGTH_LONG).show()
            
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "保存失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
}

@Composable
fun ScreenshotViewScreen(
    screenshotPath: String,
    onBack: () -> Unit,
    onSave: () -> Unit
) {
    var bitmap by remember { mutableStateOf<Bitmap?>(null) }
    val context = LocalContext.current
    
    // 加载截图
    LaunchedEffect(screenshotPath) {
        try {
            val file = File(screenshotPath)
            if (file.exists()) {
                bitmap = BitmapFactory.decodeFile(screenshotPath)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    // 缩放和平移状态
    var scale by remember { mutableFloatStateOf(1f) }
    var offset by remember { mutableStateOf(Offset.Zero) }
    
    val transformableState = rememberTransformableState { zoomChange, offsetChange, _ ->
        scale = (scale * zoomChange).coerceIn(0.5f, 3f)
        offset += offsetChange
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black)
    ) {
        // 截图显示区域
        bitmap?.let { bmp ->
            Image(
                bitmap = bmp.asImageBitmap(),
                contentDescription = "截图",
                modifier = Modifier
                    .fillMaxSize()
                    .graphicsLayer(
                        scaleX = scale,
                        scaleY = scale,
                        translationX = offset.x,
                        translationY = offset.y
                    )
                    .transformable(transformableState)
            )
        } ?: run {
            // 加载提示
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    CircularProgressIndicator(color = Color.White)
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "正在加载截图...",
                        color = Color.White,
                        fontSize = 16.sp
                    )
                }
            }
        }
        
        // 顶部控制栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
                .clip(RoundedCornerShape(8.dp))
                .background(Color.Black.copy(alpha = 0.7f))
                .padding(12.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Button(
                onClick = onBack,
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color.White.copy(alpha = 0.9f),
                    contentColor = Color.Black
                )
            ) {
                Text("返回", fontWeight = FontWeight.Bold)
            }
            
            Text(
                text = "屏幕截图",
                color = Color.White,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
            
            Button(
                onClick = onSave,
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color.Green.copy(alpha = 0.9f),
                    contentColor = Color.White
                )
            ) {
                Text("保存", fontWeight = FontWeight.Bold)
            }
        }
        
        // 底部提示信息
        Box(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(16.dp)
                .clip(RoundedCornerShape(8.dp))
                .background(Color.Black.copy(alpha = 0.7f))
                .padding(12.dp)
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "双指缩放图片",
                    color = Color.White,
                    fontSize = 14.sp
                )
                Text(
                    text = "缩放: ${String.format("%.1f", scale)}x",
                    color = Color.Gray,
                    fontSize = 12.sp
                )
            }
        }
    }
} 